<script setup lang="ts">
// 防抖
const debounce = function (fn, delay = 3000, immediate = false) {
    let timer;
    return function () {
        let context = this;
        let args = arguments;
        console.log("触发...");
        if (!immediate) {
            if (timer) {
                window.clearTimeout(timer);
            }
        } else {
            immediate = false;
            fn.call(context, ...args);
        }
        timer = window.setTimeout(fn.bind(context, ...args), delay);
    }
}

let debounceTimer;
const runnerDebounce = (immediate = false) => {
    if (debounceTimer) {
        window.clearInterval(debounceTimer);
        debounceTimer = null;
        return
    }
    debounceTimer = setInterval(debounce(handler, 3000, immediate).bind(null, 1, 2, 3), 500);

    function handler(a, b, c) {
        console.log("正式运行", a, b, c);
    }
}

// 节流
const throttle = function (fn, delay = 3000) {
    let timer;
    return function () {
        let context = this;
        let args = arguments;
        console.log("触发...");

        if (!timer) {
            timer = window.setTimeout(function () {
                fn.apply(context, args);
                timer = null;
            }, delay);
        }
    }
}
let throttleTimer;
const runnerThrottle = () => {
    if (throttleTimer) {
        window.clearInterval(throttleTimer);
        throttleTimer = null;
        return
    }
    throttleTimer = setInterval(throttle(handler, 3000).bind(null, 1, 2, 3), 500);

    function handler(a, b, c) {
        console.log("正式运行", a, b, c);
    }
}
</script>

<template>
    <el-button @click="runnerDebounce(false)">防抖</el-button>
    <el-button @click="runnerDebounce(true)">防抖立即执行</el-button>
    <el-button @click="runnerThrottle">节流</el-button>
</template>

<style lang="scss">

</style>
